package com.step.ems.common

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.step.ems.api.res.LoginRes
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.first
import javax.inject.Inject

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "ds")

class DataStoreUtil @Inject constructor(@ApplicationContext private val context: Context) {
    companion object {
        val userNameKey = stringPreferencesKey("username")
        val passwordKey = stringPreferencesKey("password")
        val accessTokenKey = stringPreferencesKey("accessToken")
        val refreshTokenKey = stringPreferencesKey("refreshToken")
    }

    private val dataStore = context.dataStore

    suspend fun saveLoginInfo(value: LoginRes) {
        dataStore.edit { preferences ->
            preferences[userNameKey] = value.username
            preferences[passwordKey] = value.password
            preferences[accessTokenKey] = value.accessToken
            preferences[refreshTokenKey] = value.refreshToken
        }
    }

    suspend fun getUsername(): String? {
        return dataStore.data.first()[userNameKey]
    }

    suspend fun getPassword(): String? {
        return dataStore.data.first()[passwordKey]
    }

    suspend fun getAccessToken(): String? {
        return dataStore.data.first()[accessTokenKey]
    }

    suspend fun getRefreshToken(): String? {
        return dataStore.data.first()[refreshTokenKey]
    }

    suspend fun logout() {
        dataStore.edit { preferences ->
            preferences.remove(accessTokenKey)
            preferences.remove(refreshTokenKey)
        }
    }
}